package com.black.utils.commons.network;

import com.black.utils.commons.pool.Pool;
import com.black.utils.commons.pool.PoolFactory;
import com.black.utils.commons.pool.PoolProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Closeable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author ylx
 */
public abstract class Sender<T> implements Closeable {
    protected Logger log = LoggerFactory.getLogger(this.getClass());
    protected final PoolProperties properties;
    protected final Pool<T> pool;

    public Sender(PoolProperties properties, Class<? extends PoolFactory<T>> factoryClass) {
        try {
            this.properties = properties;
            Constructor<? extends PoolFactory<T>> constructor = factoryClass.getConstructor(PoolProperties.class);
            PoolFactory<T> factory = constructor.newInstance(properties);
            this.pool = new Pool<>(factory, properties.getMinIdle());
        } catch (NoSuchMethodException | InvocationTargetException | InstantiationException |
                 IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public abstract boolean send(String arg);

    public void updateConfig() {
        this.pool.updateConfig();
    }

    @Override
    public void close() {
        this.pool.close();
    }
}
